﻿/*
 * Created by SharpDevelop.
 * User: notmmao
 * Date: 2015/5/29
 * Time: 15:16
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace D3AutoClick
{
	public sealed class NotificationIcon
	{
		private NotifyIcon notifyIcon;
		private ContextMenu notificationMenu;
		
		#region Initialize icon and menu
		public NotificationIcon()
		{
			notifyIcon = new NotifyIcon();
			notificationMenu = new ContextMenu(InitializeMenu());
			
			notifyIcon.DoubleClick += IconDoubleClick;
			notifyIcon.Icon = (Icon)D3AutoClick.Properties.Resources.Logo;
			notifyIcon.ContextMenu = notificationMenu;
		}
		
		private MenuItem[] InitializeMenu()
		{
			MenuItem[] menu = new MenuItem[] {
				new MenuItem("About", menuAboutClick),
				new MenuItem("Exit", menuExitClick),
			};
			return menu;
		}
		#endregion
		
		#region Main - Program entry point
		/// <summary>Program entry point.</summary>
		/// <param name="args">Command Line Arguments</param>
		[STAThread]
		public static void Main(string[] args)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			
			bool isFirstInstance;
			// Please use a unique name for the mutex to prevent conflicts with other programs
			using (Mutex mtx = new Mutex(true, "D3AutoClick", out isFirstInstance)) {
				if (isFirstInstance) {
					NotificationIcon notificationIcon = new NotificationIcon();
					notificationIcon.notifyIcon.Visible = true;
					Splash.ShowSplashScreen();
		            Thread.Sleep(1000 * 2);
		            if (Splash.SplashScreen != null)
		            {
		                Splash.SplashScreen.Dispose();
		            }
					Application.Run(Form2.Instance);
					notificationIcon.notifyIcon.Dispose();
				} else {
					// The application is already running
					// TODO: Display message box or change focus to existing application instance
					Win32Api.ShowRemote();
				}
			} // releases the Mutex
		}
		#endregion
		
		#region Event Handlers
		private void menuAboutClick(object sender, EventArgs e)
		{
			MessageBox.Show(Splash.Message, "About");
		}
		
		private void menuExitClick(object sender, EventArgs e)
		{
			Form2.Instance.Close();
			Application.Exit();
			Environment.Exit(0);
		}

		private void IconDoubleClick(object sender, EventArgs e)
		{
			Form2.Instance.Show();
			Form2.Instance.WindowState = FormWindowState.Normal;
		}
		#endregion
	}
}
